<template>
  <div id="app" v-bind:style="appDivStyle">
      <div class="context" ref="context">
           <div class="queryBox" ref="queryBox">
                <el-form :model="formQueryCondition"
                         ref="form" size="mini">
                    <el-row>
                        <!-- 角色编码 -->
                        <el-col :span="5">
                            <el-form-item :label="$t('queryLabel.role.code')"
                            :label-width="queryformLabelWidth">
                                <el-input v-model.trim="formQueryCondition.roleCode.val" class="queryItemStyle" clearable
                                        :placeholder="$t('queryLabel.role.placeholderCode')"></el-input>
                            </el-form-item>
                        </el-col>
                        <!-- 角色名称 -->
                        <el-col :span="5" :offset="1">
                            <el-form-item :label="$t('queryLabel.role.name')"   :label-width="queryformLabelWidth">
                                <el-input v-model.trim="formQueryCondition.roleName.val" class="queryItemStyle" clearable
                                        :placeholder="$t('queryLabel.role.placeholderName')">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <!-- 是否可用 -->
                        <el-col :span="5" :offset="1">
                            <el-form-item :label="$t('queryLabel.role.isEnabled')"  :label-width="queryformLabelWidth">
                                <el-select v-model="formQueryCondition.isEnable.val" class="queryItemStyle">
                                    <el-option :label="$t('label.all')" value=""></el-option>
                                    <el-option :value="drug.valueCode" :key="drug.valueCode" :label="drug.valueText" v-for="drug in enables"></el-option>
                                    <!-- <el-option :label="$t('label.available')" value="Available"></el-option>
                                    <el-option :label="$t('label.invalid')" value="Invalid"></el-option> -->
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <!-- 列表上的按钮 -->
                    <el-row>
                        <el-col :span="24">
                            <div style="text-align:right">
                                <el-form-item>
                                    <!-- 新增 -->
                                    <el-button type="primary" v-if="test('onNewBtn')" v-permission="{menuCode: menuCode, resourceCode: 'saveBtnText'}"
                                    @click="onNew('saveBtnText')">{{ $t('btnText.newBtnText') }}</el-button>
                                <!-- </el-form-item> -->
                                <!-- <el-form-item> -->
                                    <!-- 重置 -->
                                    <el-button v-permission="{menuCode: menuCode, resourceCode: 'resetBtnText'}" type="primary" @click="onReset('form')">{{ $t('btnText.resetBtnText') }}</el-button>
                                <!-- </el-form-item> -->
                                <!-- <el-form-item>
                                    <el-button type="primary" @click="onExport" icon="el-icon-download" :loading="loading">{{ $t('btnText.exportBtnText') }}</el-button>
                                </el-form-item> -->
                                <!-- <el-form-item> -->
                                    <!-- 查询 -->
                                    <el-button v-permission="{menuCode: menuCode, resourceCode: 'queryBtnText'}" type="primary" @click="onQuery('queryBtnText')" icon="el-icon-search" :loading="loading">{{ $t('btnText.queryBtnText') }}</el-button>
                                </el-form-item>
                            </div>
                        </el-col>
                    </el-row>
                </el-form>
            </div>

            <div class="dataBox" ref="dataBox">

                <transition enter-active-class="animated zoomIn" leave-active-class="animated rotateOut">
                    <el-table v-if="isInit" ref="singleTable"
                                :data="tableData"
                                :height="tableHeight"
                                @sort-change="sortChange"
                                v-loading="loading" size="mini"
                                style="width: 100%;" stripe=stripe border=border>
                        <el-table-column type="index"  width="50" fixed="left"
                                            :label="$t('table.xh')" align="center">
                        </el-table-column>
                        <el-table-column :label="$t('table.op')" fixed="left" min-width="270">
                            <template slot-scope="scope">
                                <el-button size="gv" icon="fa fa-edit" v-permission="{menuCode: menuCode, resourceCode: 'authorizeBtnText'}"
                                :loading="loading" @click="editMenu(scope.$index, scope.row,'authorizeBtnText')"
                                            >{{ $t('btnText.authorizationBtnText') }}</el-button>
                                <el-button size="gv" icon="el-icon-edit" :loading="loading"
                                v-permission="{menuCode: menuCode, resourceCode: 'editBtnText'}"
                                @click="edit(scope.$index, scope.row,'editBtnText')"
                                            >{{ $t('btnText.editBtnText') }}</el-button>
                                <!-- 恢复按钮 -->
                                <el-button size="gv" icon="el-icon-delete"
                                            v-permission="{menuCode:menuCode,resourceCode:'recoveryBtnText'}"
                                            type="danger" :loading="loading" @click="recovery(scope.$index, scope.row,'recoveryBtnText')" v-show="scope.row.isEnable=='Invalid'"
                                            >{{ $t('btnText.recoveryBtnText') }}</el-button>
                               <el-button size="gv" icon="el-icon-delete" v-show="scope.row.isEnable=='Invalid'"
                               v-permission="{menuCode: menuCode, resourceCode: 'delBtnText'}"
                                    type="danger" :loading="loading" @click="deleteRow(scope.$index, scope.row,'delBtnText')"
                                    >{{ $t('btnText.deleteBtnText') }}</el-button>
                               <el-button size="gv" icon="el-icon-delete" v-show="scope.row.isEnable=='Available'"
                               v-permission="{menuCode: menuCode, resourceCode: 'passBtnText'}"
                                    type="danger" :loading="loading" @click="logoffRow(scope.$index, scope.row,'passBtnText')"
                                    >{{ $t('btnText.logoffBtnText') }}</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="roleCode" min-width="110" fixed="left"
                                            :label="$t('table.role.code')" sortable="custom" sort-by="roleCode">
                        </el-table-column>
                        <el-table-column prop="roleName" min-width="110" fixed="left"
                                            :label="$t('table.role.name')" sortable="custom" sort-by="roleName">
                        </el-table-column>
                        <el-table-column prop="roleEnName" min-width="130"
                        :label="$t('table.role.enName')" sortable="custom" sort-by="roleEnName">
                        </el-table-column>
                        <el-table-column prop="roleDesc" min-width="150"
                        :label="$t('table.role.desc')" sortable="custom" sort-by="roleDesc">
                        </el-table-column>
                        <el-table-column prop="isEnableName" min-width="110" sortable="custom"
                        :label="$t('table.isEnabled')" sort-by="isEnable">
                        </el-table-column>

                        <el-table-column :label="$t('table.lastUpdatedBy')" min-width="120" sortable="custom" prop="modifier" sort-by="modifier">
                        </el-table-column>
                        <el-table-column :label="$t('table.lastUpdateTime')" min-width="180" sortable="custom" prop="lastUpdatedDate" sort-by="lastUpdatedDate">
                        </el-table-column>

                    </el-table>
                </transition>

            </div>
        </div>
        <div class="pageBox">
            <el-pagination @size-change="sizeChange"
                            @current-change="currentPageChange"
                            :current-page="pager.curPage"
                            :page-sizes="pager.sizes"
                            :page-size="pager.curSize"
                            :background="true"
                            layout="total, sizes, prev, pager, next, jumper" :total="pager.total">
            </el-pagination>
        </div>

         <!--编辑对话框-->
        <transition enter-active-class="animated rotateIn" leave-active-class="animated rotateOut">
            <el-dialog :title="$t('label.dialogTitle')" :visible.sync="isShowEditForm" top="5vh" :close-on-click-modal="false">
                <el-form :model="editForm" ref="editForm" size="mini"
                        :label-position="editFormPosition" status-icon=status-icon :rules="editRules">
                    <el-input v-model.trim="editForm.keyId"  v-show="false"></el-input>
                    <el-form-item :label="$t('editLabel.role.code')" :label-width="editformLabelWidth" prop="roleCode">
                        <el-input v-model.trim="editForm.roleCode" maxlength="20" :disabled="canEditCode"
                                :placeholder="$t('editLabel.role.placeholderCode')"></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('editLabel.role.name')"
                                :label-width="editformLabelWidth" prop="roleName">
                        <el-input v-model.trim="editForm.roleName" maxlength="50"
                                :placeholder="$t('editLabel.role.placeholderName')"></el-input>
                    </el-form-item>

                    <el-form-item :label="$t('editLabel.role.enName')" :label-width="editformLabelWidth" prop="roleEnName">
                        <el-input v-model.trim="editForm.roleEnName" maxlength="50"
                                :placeholder="$t('editLabel.role.placeholderEnName')"></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('editLabel.role.desc')" :label-width="editformLabelWidth" prop="roleDesc">
                        <el-input v-model="editForm.roleDesc" maxlength="100"
                                :placeholder="$t('editLabel.role.placeholderDesc')"></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('label.isEnabled')" :label-width="editformLabelWidth">
                        <el-select v-model="editForm.isEnable">
                            <!-- <el-option :label="$t('label.available')" value="Available"></el-option>
                            <el-option :label="$t('label.invalid')" value="Invalid"></el-option> -->
                            <el-option :value="drug.valueCode" :key="drug.valueCode" :label="drug.valueText" v-for="drug in enables"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer">
                    <el-button size="mini" @click="isShowEditForm = false" :loading="loading">{{ $t('btnText.cancelBtnText') }}</el-button>
                    <el-button size="mini" type="primary" @click="submitForm('editForm',currentResCode)" :loading="loading">{{ $t('btnText.saveBtnText') }}</el-button>
                </div>
            </el-dialog>
        </transition>

        <!-- 角色授权对话框 -->
        <el-dialog :title="$t('User.editLabel.placeholderRoles')" :visible.sync="isShowSelectForm" top="5vh" :close-on-click-modal="false"><!---->
            <el-form :label-width="editformLabelWidth"
                        :label-position="editFormPosition" status-icon=status-icon>
                <template>
                    <!--
                    <el-tree
                        :data="data2"
                        show-checkbox
                        default-expand-all
                        node-key="id"
                        ref="tree"
                        highlight-current
                        :props="defaultProps">
                    </el-tree>
                    -->
                    <el-tree :data="data2"
                     default-expand-all
                     highlight-current
                     ref="tree"
                     show-checkbox=show-checkbox
                     node-key="id"
                     :expand-on-click-node="true"
                     check-on-click-node

                     :props="defaultProps">
                     </el-tree>
                </template>
            </el-form>
            <div slot="footer">
                <el-button size="mini" @click="isShowSelectForm = false" :loading="loading">{{ $t('btnText.cancelBtnText') }}</el-button>
                <el-button size="mini" type="primary" @click="submitRoleAuthorize(currentResCode)" :loading="loading">{{ $t('btnText.saveBtnText') }}</el-button>
            </div>
        </el-dialog>

  </div>


</template>

<script>

import comBaseVue from '../../baseViewModel';

export default {
  mixins: [comBaseVue],
  name:'Role',
  props: {
    menuCode: String
  },
  data () {

    return {
        isShowSelectForm:false,
        isInit:false,
        tableHeight:100,
        appDivStyle:{
            height:this.$store.getters.appHeight,
        },
        enables:[],
        modelName:"com.ispr.iptv.entity.sys.SysRole",
        // 查询条件
        formQueryCondition: {
            roleCode: {
                key: 'roleCode',
                op: 'LIKE', // 操作符
                val: '' // 查询的值
            },
            isEnable: {
                key: 'isEnable',
                op: '=',
                val: ''
            },
            roleName: {
                key: 'roleName',
                op: 'LIKE',
                val: ''
            },
            isEnable: {
                key: 'isEnable',
                op: '=', // 操作符
                val: 'Available'
            },
        },

        // 编辑面板绑定的对象
        editForm: {
            keyId: 0,
            version: 0,
            roleCode: "",
            roleName: "",
            roleEnName: "",
            roleDesc: "",
            isEnable: "Available"
        },
        // 编辑面板的验证规则
        editRules: {
            roleCode: [{ required: true, message: this.$i18n.t('rules.role.code'), trigger: 'blur' }],
            roleName: [{ required: true, message: this.$i18n.t('rules.role.name'), trigger: 'blur' }]
        },
        data2: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        }
    }
  },
  methods:{
      test:function(btnCode){
          return true;
        },
    // 新增
    onNew: function(rescode) {

        this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        this.isShowEditForm = true;
        if (this.$refs['editForm']) {
            this.$refs['editForm'].resetFields();
        }
        this.editForm.keyId = "";
        this.editForm.version = "";
        this.editForm.roleCode = "";
        this.editForm.roleName = "";
        this.editForm.roleDesc = "";
        this.editForm.roleEnName = "";
        this.editForm.isEnable = "Available";
        this.curCommand = "SaveNew";
        this.canEditCode = false;
    },

     // 重置
    onReset:function(){
        if (this.$refs['form']) {
            this.$refs['form'].resetFields();
        }
        this.formQueryCondition.roleCode.val = "";
        this.formQueryCondition.isEnable.val = "";
        this.formQueryCondition.roleName.val = "";
    },

     // 为状态下拉框赋值
    findEnables: function() {
        this.findByTypeCode("10001",this.setEnables)
    },
    // 查询状态下拉框数据成功后的回调
    setEnables: function(isSuccess,json) {
        try{
            if (isSuccess) {
                this.enables = [];
                for (var i = 0; i < json.data.length; i++) {
                    this.enables.push(json.data[i]);
                }
            }
            else {
                this.$message.error(json.msg);
            }
        }
        catch(e){
            alert(e);
        }
    },

    // 授权按钮单击事件
    editMenu: function(index, row,rescode) {
         this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        this.keyId = row.keyId;
        this.isShowSelectForm = true;//将编辑显示出来
        if(this.$refs!=null && this.$refs.tree!=null){
            this.$refs.tree.setCheckedNodes([]);
        }
        var queryRequest = {
                className: "com.ispr.iptv.entity.sys.RoleResourceEntity",//修改为被查询的实体地址
                opKey: "Query",//后台编写相应的接口实现方法，主要负责转化类型
                params: [{"key":"roleId","op":"=","val":row.keyId},{"key":"isEnable","op":"=","val":"Available"}],
                //sort: [{"col":"keyId","order":"Desc"}],
                userInfo: this.getUserInfo()
            };
            // let headersObj = {
            //     'Content-Type': 'application/json',
            //     'Authorization': 'Bearer ' + this.getUserInfo().tokenCode,
            //     'X-AOHO-UserId': this.getUserInfo().keyID
            //   };
              if (this.isExistResourceCode(this)) {
                this.headersObj['X-AOHO-Resource'] = this.menuCode + ',' + this.currentResCode;
              };
            var _this = this;
            _this.axios.post('/api/query', queryRequest, {headers: this.headersObj})
                .then(function(res) {
                    if (res.data.code == "SUCCESS") {
                        // _this.isShowSelectForm = true;//将编辑显示出来
                        _this.$refs.tree.setCheckedNodes(res.data.data);
                    } else {
                        _this.$message.error(res.data.msg);
                    }
                })
                .catch(function(error) {
                    console.log(error);
                    _this.$message.error(error);
                });

    },

    //角色授权提交
    submitRoleAuthorize: function(rescode){

        this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        // console.log(this.$refs.tree.getCheckedKeys());
        var requestArgs = {
                commandCode: "roleResourceAuthorize",
                className: this.modelName,
                commandArgs: "Default",
                commandBody: {"keyId":this.keyId, "resourceList":this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys())},
                userInfo: this.getUserInfo()
            };
            // let headersObj = {
            //     'Content-Type': 'application/json',
            //     'Authorization': 'Bearer ' + this.getUserInfo().tokenCode,
            //     'X-AOHO-UserId': this.getUserInfo().keyID
            //   };
            if (this.isExistResourceCode(this)) {
            this.headersObj['X-AOHO-Resource'] = this.menuCode + ',' + this.currentResCode;
            };
            var _this = this;
            this.axios.post('/api/execute', requestArgs, {headers: this.headersObj} )
                .then(function(res) {
                    if (res.data.code == "SUCCESS") {
                        _this.isShowSelectForm = false;
                        _this.$message({message: _this.$i18n.t("message.successTip"),type: 'success'});
                        _this.onQuery();
                    } else {
                        _this.$message({ message: res.msg,type: 'warning'});
                    }
                })
                .catch(function(error) {
                    console.log(error);
                    _this.$message({message:error, type: 'warning' });
                });
    },

    // 编辑按钮回调事件
    editCallback: function(isSuccess,json) {
        if(isSuccess){
            this.curCommand = "PartialUpdateProc";
            this.isShowEditForm = true;
            if (this.$refs['editForm']) {
                this.$refs['editForm'].resetFields();
            }
            this.editForm.keyId = json.keyId;
            this.editForm.version = json.version;
            this.editForm.roleCode = json.roleCode;
            this.editForm.roleName = json.roleName;
            this.editForm.roleDesc = json.roleDesc;
            this.editForm.roleEnName = json.roleEnName;
            this.editForm.isEnable = json.isEnable;
            this.canEditCode = true;
        }
        else{
            this.$message({
                message: json.msg,
                type: 'warning'
                });
        }
    },
    //恢复按钮
    recovery: function(index, row,rescode) {
     this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        var _this = this;
        this.$confirm(this.$i18n.t("message.confirmNormalMessage"),
            this.$i18n.t("message.confirmTitle"), {
            confirmButtonText: this.$i18n.t("message.yes"),
            cancelButtonText: this.$i18n.t("message.cancel"),
            type: "warning",
            callback: function (action, instance) {
                if (action == "confirm") {
                    var commandBody = {  "keyId": row.keyId, "version": row.version, isEnable: "Available" };
                    _this.loading = true;
                    _this.procCommand("RecoveryProc",
                            _this.modelName,
                            "default",
                            commandBody,
                            null,
                            _this.submitFormCallback);
                }

            }
        });
    },

    //删除
    deleteRow: function(index, row,rescode){
      this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        var _this = this;
        this.$confirm(this.$i18n.t("message.confirmDelMessage"),
            this.$i18n.t("message.confirmTitle"), {
            confirmButtonText: this.$i18n.t("message.yes"),
            cancelButtonText: this.$i18n.t("message.cancel"),
            type: "warning",
            callback: function (action, instance) {
                if (action == "confirm") {
                    var commandBody = {  "keyId": row.keyId, "version": row.version };
                    _this.loading = true;
                    _this.procCommand("DelRoleProc",
                            _this.modelName,
                            "default",
                            commandBody,
                            null,
                            _this.submitFormCallback);
                }

            }
        });
    },

    // 加载权限树数据
    settree: function(index, row) {
        var queryRequest = {
                className: "com.ispr.iptv.entity.sys.MenuResource",//修改为被查询的实体地址
                opKey: "MenuParent",//后台编写相应的接口实现方法，主要负责转化类型
                params: [{"key":"menuParentCode","op":"=","val":"root"},{"key":"isEnable","op":"=","val":"Available"}],
                //sort: [{"col":"keyId","order":"Desc"}],
                userInfo: this.getUserInfo()
            };
            var _this = this;
            this.axios.post('/api/query', queryRequest, {headers: this.headersObj})
                .then(function(res) {
                    if (res.data.code == "SUCCESS") {
                        _this.data2 = res.data.data;
                    } else {
                        _this.$message.error(res.data.msg);
                    }
                })
                .catch(function(error) {
                    console.log(error);
                    _this.$message.error(error);
                });
    },
      enterDown(){
          var g=this
          if(g.isShowEditForm){
              g.submitForm('editForm',g.currentResCode)
          }else if(g.isShowSelectForm){
              g.submitRoleAuthorize(g.currentResCode)
          }else if(!g.loading){
              g.onQuery()
          }
      },


  },
  mounted: function mounted() {
    this.findEnables();
    this.settree();
    this.tableHeight = this.$refs.context.offsetHeight - this.$refs.queryBox.offsetHeight;
    this.isInit = true;
    this.onQuery();

  }
}


</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
